import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'
import { SentimentData } from '@/api'

// 定义查询参数接口
interface QueryParams {
  keyword?: string
  platform?: string
  sentiment_type?: string
  start_date?: string
  end_date?: string
  page?: number
  page_size?: number
}

export const useSentimentStore = defineStore('sentiment', () => {
  // 状态
  const loading = ref(false)
  const sentiments = ref<SentimentData[]>([])
  const total = ref(0)
  const pageSize = ref(10)
  const currentPage = ref(1)
  const currentSentiment = ref<SentimentData | null>(null)

  // 获取舆情数据列表
  const fetchSentiments = async (params: QueryParams = {}) => {
    loading.value = true
    try {
      const response = await api.getSentiments({
        keyword: params.keyword || '',
        platform: params.platform || '',
        sentiment_type: params.sentiment_type || '',
        start_date: params.start_date || '',
        end_date: params.end_date || '',
        page: params.page || currentPage.value,
        page_size: params.page_size || pageSize.value
      })
      sentiments.value = response.results
      total.value = response.count
      return response
    } catch (error) {
      console.error('获取舆情数据失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取舆情详情
  const fetchSentimentDetail = async (id: number) => {
    loading.value = true
    try {
      const response = await api.getSentimentDetail(id)
      currentSentiment.value = response
      return response
    } catch (error) {
      console.error('获取舆情详情失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除舆情
  const deleteSentiment = async (id: number) => {
    try {
      const response = await api.deleteSentiment(id)
      return response
    } catch (error) {
      console.error('删除舆情失败:', error)
      throw error
    }
  }

  // 设置当前页
  const setCurrentPage = (page: number) => {
    currentPage.value = page
  }

  // 设置每页条数
  const setPageSize = (size: number) => {
    pageSize.value = size
  }

  return {
    loading,
    sentiments,
    total,
    pageSize,
    currentPage,
    currentSentiment,
    fetchSentiments,
    fetchSentimentDetail,
    deleteSentiment,
    setCurrentPage,
    setPageSize
  }
}) 